<template>
  <div class="box">
    <el-button type="primary" plain  @click="onOpen()" icon="el-icon-plus" size="mini">添加商品类别</el-button>
    <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="isDelete" @click="delNode()">批量删除</el-button>
    <!-- 用于控制多选框是否为严格模式。严格模式下，只有叶子节点才能被选中，非叶子节点只能用来展开或折叠子节点。
      如果设置为  true ，则表示开启严格模式；如果设置为  false ，则表示关闭严格模式。 -->
    <el-button type="primary" plain icon="el-icon-check" size="mini"  @click="switchCheckStrictly(1)">父子关联</el-button>
    <el-button type="primary" plain icon="el-icon-close" size="mini"  @click="switchCheckStrictly(2)">取消关联</el-button>
    <el-dialog :visible.sync="dialogVisible"  title="添加商品类别">
      <el-form ref="categoryForm" :model="categoryData" :rules="rules" size="small" label-width="100px">
        <el-form-item label="名称" prop="cname">
          <el-input v-model="categoryData.cname" placeholder="请输入名称" :maxlength="11" show-word-limit clearable
                    prefix-icon='el-icon-user-solid' :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="上级机构" prop="parentId">
          <el-select v-model="categoryData.parentId" placeholder="请输入上级机构" clearable :style="{width: '100%'}">
            <!-- 循环中使用:key ：唯一标识 ，一般使用id -->
            <el-option
              v-for="c in categoryList"
              :key="c.id"
              :label="c.cname"
              :value="c.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="categoryData.sort" placeholder="请输入排序" :maxlength="11" show-word-limit clearable
                    prefix-icon='el-icon-sort' :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="分类图标" prop="categoryImg">
          <uploadImage v-model="categoryData.categoryImg"></uploadImage>
        </el-form-item>
        <el-form-item label="备注" prop="mark">
          <el-input
            v-model="categoryData.mark"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-form-item label="分类级别" prop="level">
          <el-select v-model="categoryData.level" placeholder="请选择分类级别" style="width: 100%" clearable>
            <el-option label="一级分类" :value="1"></el-option>
            <el-option label="二级分类" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
    <el-row :gutter="10">
      <el-col :span="100">
        <el-card class="box-card">
          <!--   expand-on-click-node 是否在点击节点的时候展开或者收缩节点，
          默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。-->
          <el-tree
            class="filter-tree"
            :data="categoryTree"
            :props="props"
            show-checkbox
            @check-change="handleCheckChange"
            highlight-current
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            :selectedKeys="selectedKeys"
            :checkStrictly="checkStrictly"
            ref="tree">
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card class="box-card" v-if="selectedKeys!=0">
          <el-form ref="queryForm" :model="queryForm" :rules="rules" label-width="80px">
            <el-form-item label="名称" prop="cname">
              <el-input v-model="queryForm.cname"></el-input>
            </el-form-item>
            <el-form-item label="上级机构">
              <el-select v-model="queryForm.parentId" placeholder="请选择上级机构" :style="{width: '100%'}" clearable>
                <!-- 循环中使用:key ：唯一标识 ，一般使用id -->
                <el-option
                  v-for="c in categoryList"
                  :key="c.id"
                  :label="c.cname"
                  :value="c.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="排序">
              <el-input v-model="queryForm.sort"></el-input>
            </el-form-item>
            <el-form-item label="分类图标" prop="categoryImg">
                <uploadImage  v-model="queryForm.categoryImg" ></uploadImage>
            </el-form-item>
            <el-form-item label="备注" prop="mark">
              <el-input
                v-model="queryForm.mark"
                placeholder="请输入备注"
                clearable
              />
            </el-form-item>
            <el-form-item label="分类级别">
              <el-select v-model="queryForm.level" placeholder="请输入分类级别" style="width: 100%" clearable>
                <el-option label="一级分类" :value="1"></el-option>
                <el-option label="二级分类" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-refresh" @click="reset('queryForm')">重置</el-button>
              <el-button type="primary" @click="save('queryForm')" icon="el-icon-edit-outline">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card v-else>
          <el-empty description="请先选择一个类别"></el-empty>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import {
  addCategory,
  categoryTree,
  delCategory,
  getCategory,
  listCategory,
  updateCategory
} from "@/api/ruoyi-goods/category";
import uploadImage from "@/components/ImageUpload/index.vue";

export default {
  name: "Category",
  components: {uploadImage},
  data() {
    return {
      dialogVisible: false, //控制模态框是否显示
      originalQueryForm: {}, // 保存最初的表单数据
      queryForm: {
        cname:'',
        parentId: '',
        sort: '',
        categoryImg: '',
        mark: '',
        level: ''
      },
      selectedKeys:[],
      props: {
        children: "child",
        label: "cname",
      },
      count: 1,
      empty:{parentId: 0},
      categoryTree:[],
      categoryList:[],//类别列表用来绑定下拉框
      categoryData: {
        cname: '',
        parentId: 0,
        sort: '',
        categoryImg:'',
        mark:'',
        level: '',
      },
      rules: {
        cname: [{
          required: true,
          message: '请输入名称',
          trigger: 'blur'
        }],
        parentId: [{
          required: true,
          message: '请选择上级机构',
          trigger: 'blur'
        }],
        level: [{
          required: true,
          message: '请选择分类级别',
          trigger: 'blur'
        }]
      },
      multipleSelection:[],//选中的删除数组
      checkStrictly:true,
    }
  },
  computed:{
    isDelete(){
      return this.multipleSelection.length==0;
    },
  },
  created() {
    this.getCategoryTree();
    this.getCategoryList();
  },
  methods: {
    onOpen() {
      this.dialogVisible = true;
      this.categoryData = JSON.parse(JSON.stringify(this.empty));
    },
    onClose() {
      this.$refs['categoryForm'].resetFields()
    },
    close() {
      this.dialogVisible=false;
    },
    //获取类别树
    getCategoryTree() {
      categoryTree().then(response =>{
        this.categoryTree = response.data;
      })
    },
    //获取类别数据
    getCategoryList(){
      listCategory().then(response => {
        this.categoryList = response.data;
      })
    },
    handleConfirm() {
      this.$refs['categoryForm'].validate(async valid => {
        if (!valid) return
        addCategory(this.categoryData).then(response => {
          this.getCategoryTree();
          this.getCategoryList();
          this.dialogVisible=false;
          this.close();
        })
      })
    },
    handleCheckChange(val) {
      // val 是一个单独的值，可以使用数组的 push 方法将其添加到一个新的数组中
      this.multipleSelection.push(val);
      console.log(this.multipleSelection);
    },
    //树形菜单点击事件
    handleNodeClick(data) {
      this.queryForm.id = data.id;
      getCategory(this.queryForm.id).then(response => {
        this.queryForm=response.data;
        this.selectedKeys = this.queryForm.id;
        // 将表单数据保存到 originalQueryForm 中
        this.originalQueryForm = JSON.parse(JSON.stringify(this.queryForm));
      })
    },
    save(){
      this.$refs['queryForm'].validate( valid => {
        if (!valid) return
        updateCategory(this.queryForm).then(response => {
          this.getCategoryTree();
          this.getCategoryList();
        })
      })
    },
    delNode(){
      const selectedNodes = this.$refs.tree.getCheckedNodes();
      this.selectedNodes = selectedNodes.map(node => node.id);
      let nodes=this.selectedNodes.join(',');
      this.dels(nodes);
      this.getCategoryTree();
    },
    dels(ids) {
      console.log(ids);
      this.$confirm(`确认要删除ids='${ids}'对应的信息吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delCategory(ids).then(response => {
          this.getCategoryList();
          this.$message({
            type: 'info',
            message: '删除成功'
          });
          this.getCategoryTree();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      });
    },

    switchCheckStrictly (v) {
      if(v==1){
        this.checkStrictly = false
      }else if(v==2){
        this.checkStrictly = true
      }
    },
    reset(formName){
      if(this.$refs[formName]){
        console.log(this.queryForm);
        //先将JSON字符串转为js对象,再转为JSON格式字符串，重置表单数据
        this.queryForm = JSON.parse(JSON.stringify(this.originalQueryForm));
        //同时重置表单的验证规则
        this.$refs[formName].resetFields();
      }
    },
  }
}

</script>
<style>
.box-card {
  width: 550px;
}
.box{
  padding: 20px;
}
</style>

